//
//  zz.swift
//  SwiftCountdownButtonDemo
//
//  Created by 郑东喜 on 2016/11/27.
//  Copyright © 2016年 Gesen. All rights reserved.
//

import UIKit
let  NUMSS = 60
protocol sendBtnDelegate:NSObjectProtocol {
    func whenSendBtnClicked(button:zz) -> Void
}

class zz: UIButton {
    
    //    定时器
    var  i = NUMSS
    var myTimer:Timer?
    weak var delegate:sendBtnDelegate!
    var  currentColor:UIColor?
    
    //    初始化控件
    func initwith(frame:CGRect,color:UIColor,title:String,superView:UIView,delegate:sendBtnDelegate) -> Void {
        self.frame = frame;
        self.backgroundColor = color
        self.setTitle(title, for: UIControlState.normal)
        self.addTarget(self, action: #selector(CodeButtonTapped), for: UIControlEvents.touchUpInside)
        superView.addSubview(self)
        self.delegate = delegate
        self.isUserInteractionEnabled = true
        self.currentColor = color
    }
    //    点击变为不可用状态
    func CodeButtonTapped(button:zz)
    {
        button.setTitle("重发(60)", for: UIControlState.disabled)
        button.titleLabel?.adjustsFontSizeToFitWidth = true
        button.backgroundColor=UIColor.lightGray
        button.isEnabled=false
        myTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(tiemrBengin), userInfo: button, repeats: true)
        //        代理实现方法
        self.delegate.whenSendBtnClicked(button: button)
    }
    

    
    func  tiemrBengin(timer:Timer)
    {    i -= 1
        let  button = timer.userInfo as! zz
        button.setTitle(String(format: "重发(%d)",i), for: UIControlState.disabled)
        button.backgroundColor=UIColor.lightGray
        if i == 0 {
            timer.invalidate()
            button.isEnabled = true
            button.backgroundColor = self.currentColor
            i = NUMSS
        }

    }
    
    
}

